<template>
  <div class="file-upload">
    <!-- 上传区域 -->
    <div ref="dropZone" class="upload-zone"
         :class="{
        'upload-zone--dragover': isDragOver,
        'upload-zone--disabled': disabled || isUploading
      }"
         @click="handleClickUpload"
         @drop="handleDrop"
         @dragover="handleDragOver"
         @dragleave="handleDragLeave">
      <div class="upload-zone__content">
        <el-icon class="upload-zone__icon" size="48">
          <UploadFilled/>
        </el-icon>
        <div class="upload-zone__text">
          <p class="upload-zone__title">{{ dragText }}</p>
          <p class="upload-zone__subtitle">支持 {{ allowedTypes.join('、') }} 格式， 单个文件不超过 {{
              dynamicMaxFileSize
            }}MB</p>
        </div>
      </div>
      <input ref="fileInput" type="file" :multiple="limit > 1" :accept="acceptTypes" @change="handleFileSelect"
             style="display: none"/>
    </div>


    <!-- 已上传文件列表 -->
    <div class="file-list" v-if="completedFiles.length > 0">
      <div class="list-title">已上传文件 ({{ completedFiles.length }})</div>
      <div 
        v-for="(file, index) in completedFiles" 
        :key="file.id" 
        class="file-item"
      >
        <div class="file-name">{{ file.name }}</div>
        <div class="file-actions">
          <div class="file-status">
            <!-- 空的状态区域，保持布局一致 -->
          </div>
          <div class="action-buttons">
            <el-button 
              class="remove-btn" 
              @click="removeCompletedFile(index)"
              :icon="Close"
              circle
              size="small"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 上传中的文件列表 -->
    <div class="uploading-list" v-if="uploadQueue.length > 0">
      <div class="list-title">上传中 ({{ uploadQueue.length }})</div>
      <div 
        v-for="(file, index) in uploadQueue" 
        :key="file.id" 
        class="file-item"
        :class="{ 'file-item--error': file.status === 'error' }"
      >
        <div class="file-name">{{ file.name }}</div>
        <div class="file-actions">
          <div class="file-status">
            <template v-if="file.status === 'waiting'">
              <span class="status-text">等待中</span>
            </template>
            <template v-else-if="file.status === 'uploading'">
              <span class="status-text">{{ Math.round(file.progress) }}%</span>
            </template>
            <template v-else-if="file.status === 'completed'">
              <span class="status-text success">完成</span>
            </template>
            <template v-else-if="file.status === 'error'">
              <span class="status-text error">失败</span>
            </template>
          </div>
          <div class="action-buttons">
            <el-button 
              class="remove-btn" 
              @click="removeFile(index)"
              :icon="Close"
              circle
              size="small"
            />
            <el-button 
              v-if="file.status === 'waiting' && !isUploading" 
              class="upload-btn-small" 
              @click="startSingleUpload(file)"
              :icon="Upload"
              circle
              size="small"
              type="primary"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, nextTick, onMounted, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Document, UploadFilled, Close, Upload} from '@element-plus/icons-vue'
import {createUploadManager, formatFileSize, generateFileId} from '@/utils/upload-utils'

// Props
const props = defineProps({
  // v-model 值，支持字符串（逗号分隔）和数组
  modelValue: {
    type: [String, Array],
    default: () => []
  },
  // 最大文件数量
  limit: {
    type: Number,
    default: 5
  },
  // 单个文件最大大小(MB)
  maxFileSize: {
    type: Number,
    default: 1024
  },
  // 允许的文件类型
  allowedTypes: {
    type: Array,
    default: () => ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar']
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 分片大小(MB)
  chunkSize: {
    type: Number,
    default: 5
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'upload-success', 'upload-error', 'upload-progress'])

// 响应式数据
const dropZone = ref(null)
const fileInput = ref(null)
const isDragOver = ref(false)
const isUploading = ref(false)
const uploadQueue = ref([])
const completedFiles = ref([])
const storageConfigs = ref([])
const selectedConfigId = ref(null)
const uploadDir = ref('')
// 动态文件大小限制（来自存储配置）
const dynamicMaxFileSize = ref(props.maxFileSize)

// 计算属性
const acceptTypes = computed(() => {
  return props.allowedTypes.map(type => `.${type}`).join(',')
})

const dragText = computed(() => {
  if (props.disabled) return '上传已禁用'
  if (isUploading.value) return '上传中...'
  return '拖拽文件到此处或点击选择文件'
})

// 处理文件选择
function handleFileSelect(event) {
  const files = Array.from(event.target.files)
  addFilesToQueue(files)
  // 清空input
  event.target.value = ''
}

// 创建上传管理器（延迟初始化，避免循环依赖）
let uploadManager = null

function getUploadManager() {
  if (!uploadManager) {
    uploadManager = createUploadManager({
      allowedTypes: props.allowedTypes,
      maxFileSize: dynamicMaxFileSize.value,
      maxCount: props.limit,
      chunkSize: props.chunkSize,
      currentCount: () => completedFiles.value.length,
      queueCount: () => uploadQueue.value.length,
      disabled: () => props.disabled,
      isUploading: () => isUploading.value,
      canAddMore: () => uploadQueue.value.length < props.limit,
      onDragOver: (isDragOver) => {
        isDragOver.value = isDragOver
      },
      onDragLeave: (isDragOver) => {
        isDragOver.value = isDragOver
      },
      onDrop: (files) => addFilesToQueue(files)
    })
  }
  return uploadManager
}

// 拖拽处理器
function handleDragOver(event) {
  event.preventDefault()
  if (!props.disabled && !isUploading.value && uploadQueue.value.length < props.limit) {
    isDragOver.value = true
  }
}

function handleDragLeave(event) {
  event.preventDefault()
  isDragOver.value = false
}

function handleDrop(event) {
  event.preventDefault()
  isDragOver.value = false

  if (props.disabled || isUploading.value || uploadQueue.value.length >= props.limit) return

  const files = Array.from(event.dataTransfer.files)
  addFilesToQueue(files)
}

// 点击上传区域
function handleClickUpload() {
  if (props.disabled || isUploading.value) return
  fileInput.value.click()
}

// 添加文件到队列
function addFilesToQueue(files) {
  const manager = getUploadManager()
  const {validFiles, errors} = manager.validator.validateFiles(files, uploadQueue.value)

  // 显示错误信息
  errors.forEach(error => ElMessage.error(error))

  // 处理有效文件
  const processedFiles = validFiles.map(file => ({
    id: generateFileId(),
    file: file,
    name: file.name,
    size: file.size,
    type: file.type,
    status: 'waiting',
    progress: 0,
    uploadMethod: manager.determineUploadMethod(file),
    supportDirectUpload: false,
    errorMessage: '',
    filePath: '',
    uploadId: '',
    etags: []
  }))

  uploadQueue.value.push(...processedFiles)
}

// 移除文件
function removeFile(index) {
  uploadQueue.value.splice(index, 1)
}

// 移除已完成的文件
function removeCompletedFile(index) {
  completedFiles.value.splice(index, 1)
}

// 开始单个文件上传
async function startSingleUpload(fileObj) {
  // 确保存储配置已加载
  if (storageConfigs.value.length === 0) {
    try {
      await loadStorageConfigs()
    } catch (error) {
      ElMessage.error('加载存储配置失败，请检查网络连接')
      return
    }
  }

  if (!selectedConfigId.value) {
    if (storageConfigs.value.length > 0) {
      const {getDefaultConfigId} = await import('@/store/modules/fileConfig')
      selectedConfigId.value = await getDefaultConfigId(storageConfigs.value)
    } else {
      ElMessage.error('没有可用的存储配置，请先在系统管理中配置存储')
      return
    }
  }

  try {
    const config = storageConfigs.value.find(c => c.configId === selectedConfigId.value)
    if (!config) {
      throw new Error('未找到存储配置信息')
    }

    fileObj.status = 'uploading'
    fileObj.progress = 0
    fileObj.errorMessage = ''

    if (fileObj.uploadMethod === 'chunk') {
      await uploadFileWithChunks(fileObj, config)
    } else {
      await uploadFileNormally(fileObj, config)
    }

    fileObj.status = 'completed'
    fileObj.progress = 100

    // 使用后端返回的URL，如果没有则尝试获取
    let url = fileObj.url
    if (!url && fileObj.filePath) {
      try {
        url = await getUploadManager().getImageUrl(fileObj.filePath, selectedConfigId.value)
        fileObj.url = url
      } catch (error) {
        url = fileObj.filePath
      }
    }

    // 移动到已完成列表
    completedFiles.value.push({
      id: fileObj.id,
      name: fileObj.name,
      filePath: fileObj.filePath,
      url: url || fileObj.filePath,
      size: fileObj.size
    })

    // 从队列中移除
    const index = uploadQueue.value.findIndex(f => f.id === fileObj.id)
    if (index > -1) {
      uploadQueue.value.splice(index, 1)
    }

    emit('upload-success', {
      file: fileObj,
      filePath: fileObj.filePath
    })

    ElMessage.success('上传成功')

  } catch (error) {
    fileObj.status = 'error'
    fileObj.errorMessage = error.message || '上传失败'

    emit('upload-error', {
      file: fileObj,
      error: error
    })

    ElMessage.error('上传失败：' + error.message)
  }
}

// 开始上传
async function startUpload() {
  // 确保存储配置已加载
  if (storageConfigs.value.length === 0) {
    try {
      await loadStorageConfigs()
    } catch (error) {
      ElMessage.error('加载存储配置失败，请检查网络连接')
      return
    }
  }

  if (!selectedConfigId.value) {
    // 如果没有选择配置，使用默认配置
    if (storageConfigs.value.length > 0) {
      // 使用便捷方法获取默认配置ID
      const {getDefaultConfigId} = await import('@/store/modules/fileConfig')
      selectedConfigId.value = await getDefaultConfigId(storageConfigs.value)
    } else {
      ElMessage.error('没有可用的存储配置，请先在系统管理中配置存储')
      return
    }
  }

  if (uploadQueue.value.length === 0) {
    ElMessage.warning('没有文件需要上传')
    return
  }

  isUploading.value = true

  try {
    // 获取存储配置信息
    const config = storageConfigs.value.find(c => c.configId === selectedConfigId.value)

    // 逐个上传文件
    for (const fileObj of uploadQueue.value) {
      if (fileObj.status === 'completed') continue

      try {
        fileObj.status = 'uploading'
        fileObj.progress = 0
        fileObj.errorMessage = ''

        if (fileObj.uploadMethod === 'chunk') {
          await uploadFileWithChunks(fileObj, config)
        } else {
          await uploadFileNormally(fileObj, config)
        }

        fileObj.status = 'completed'
        fileObj.progress = 100

        // 使用后端返回的URL，如果没有则尝试获取
        let url = fileObj.url
        if (!url && fileObj.filePath) {
          try {
            url = await getUploadManager().getImageUrl(fileObj.filePath, selectedConfigId.value)
            fileObj.url = url
          } catch (error) {
            url = fileObj.filePath
          }
        }

        // 移动到已完成列表
        completedFiles.value.push({
          id: fileObj.id,
          name: fileObj.name,
          filePath: fileObj.filePath,
          url: url || fileObj.filePath, // 优先使用完整URL
          size: fileObj.size
        })

        emit('upload-success', {
          file: fileObj,
          filePath: fileObj.filePath
        })

      } catch (error) {
        fileObj.status = 'error'
        fileObj.errorMessage = error.message || '上传失败'

        emit('upload-error', {
          file: fileObj,
          error: error
        })
      }
    }

    ElMessage.success('上传完成')

  } catch (error) {
    ElMessage.error('上传过程中发生错误：' + error.message)
  } finally {
    isUploading.value = false
  }
}

// 普通上传
async function uploadFileNormally(fileObj, config) {
  const onProgress = (progress) => {
    emit('upload-progress', {file: fileObj, progress})
  }

  await getUploadManager().uploadFileNormally(
      fileObj, config, selectedConfigId.value, uploadDir.value, onProgress
  )
}


// 分片上传
async function uploadFileWithChunks(fileObj, config) {
  const onProgress = (progress) => {
    emit('upload-progress', {file: fileObj, progress})
  }

  // 将MB转换为字节
  const chunkSizeBytes = props.chunkSize * 1024 * 1024

  await getUploadManager().uploadFileWithChunks(
      fileObj, config, selectedConfigId.value, uploadDir.value, chunkSizeBytes, onProgress
  )
}


// 取消上传
async function cancelUpload() {
  try {
    await ElMessageBox.confirm('确定要取消上传吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 取消所有正在进行的分片上传
    for (const fileObj of uploadQueue.value) {
      if (fileObj.status === 'uploading' && fileObj.uploadId) {
        try {
          await abortMultipartUpload(fileObj.filePath, fileObj.uploadId, selectedConfigId.value)
        } catch (error) {
          console.error('取消分片上传失败:', error)
        }
      }
      if (fileObj.status === 'uploading') {
        fileObj.status = 'waiting'
        fileObj.progress = 0
      }
    }

    isUploading.value = false
    ElMessage.info('已取消上传')

  } catch (error) {
    // 用户取消确认
  }
}

// 重试上传
function retryUpload(fileObj) {
  fileObj.status = 'waiting'
  fileObj.progress = 0
  fileObj.errorMessage = ''
}

// 清空结果
function clearResults() {
  completedFiles.value = []
  uploadQueue.value = uploadQueue.value.filter(file => file.status !== 'completed')
}

// 复制路径
function copyPath(path) {
  getUploadManager().copyPath(path)
}

// 复制文件URL
async function copyFileUrl(file) {
  try {
    let url = ''

    // 检查是否已有完整URL
    if (file.url && file.url.startsWith('http')) {
      url = file.url
    } else if (file.filePath) {
      // 通过API获取完整URL
      url = await getUploadManager().getImageUrl(file.filePath, selectedConfigId.value)
    } else if (file.url) {
      // file.url 可能是相对路径，通过API获取完整URL
      url = await getUploadManager().getImageUrl(file.url, selectedConfigId.value)
    }

    if (url) {
      await navigator.clipboard.writeText(url)
      ElMessage.success('文件URL已复制到剪贴板')
    } else {
      ElMessage.error('文件URL为空')
    }
  } catch (error) {
    ElMessage.error('复制文件URL失败: ' + error.message)
  }
}

// 加载存储配置
async function loadStorageConfigs() {
  try {
    storageConfigs.value = await getUploadManager().loadStorageConfigs()
    
    if (!selectedConfigId.value && storageConfigs.value.length > 0) {
      // 使用便捷方法获取默认配置ID
      const {getDefaultConfigId} = await import('@/store/modules/fileConfig')
      selectedConfigId.value = await getDefaultConfigId(storageConfigs.value)
    }

    // 更新动态文件大小限制
    updateDynamicMaxFileSize()
  } catch (error) {
    throw error // 重新抛出错误，让调用者处理
  }
}

// 更新动态文件大小限制
function updateDynamicMaxFileSize() {
  if (selectedConfigId.value && storageConfigs.value.length > 0) {
    const config = storageConfigs.value.find(c => c.configId === selectedConfigId.value)
    if (config && config.maxFileSize) {
      // 将字节转换为MB
      dynamicMaxFileSize.value = Math.floor(config.maxFileSize / (1024 * 1024))
    }
  }
  // 重置上传管理器以使用新的文件大小限制
  uploadManager = null
}

// v-model 相关函数
function initFromModelValue() {
  if (!props.modelValue) {
    completedFiles.value = []
    return
  }

  let files = []
  if (typeof props.modelValue === 'string') {
    files = props.modelValue.split(',').filter(path => path.trim())
  } else if (Array.isArray(props.modelValue)) {
    files = props.modelValue
  }

  completedFiles.value = files.map((fileData, index) => {
    let filePath, url, fileName
    
    if (typeof fileData === 'string') {
      // 如果是字符串，可能是URL或相对路径
      filePath = fileData
      url = fileData
      fileName = getFileNameFromPath(fileData)
    } else if (typeof fileData === 'object' && fileData !== null) {
      // 如果是对象，提取相关字段
      filePath = fileData.filePath || fileData.url
      url = fileData.url || fileData.filePath
      fileName = fileData.name || getFileNameFromPath(filePath)
    } else {
      // 其他情况的兜底处理
      filePath = String(fileData)
      url = filePath
      fileName = getFileNameFromPath(filePath)
    }
    
    return {
      id: `existing_${index}`,
      name: fileName,
      filePath: filePath,
      url: url, // 保持原有的URL信息
      size: 0 // 已存在的文件无法获取大小
    }
  })
}

function updateModelValue() {
  const fileUrls = completedFiles.value
      .filter(file => file.url || file.filePath)
      .map(file => file.url || file.filePath) // 优先使用URL，如果没有则使用filePath

  if (typeof props.modelValue === 'string') {
    emit('update:modelValue', fileUrls.join(','))
  } else {
    emit('update:modelValue', fileUrls)
  }
}

function getFileNameFromPath(filePath) {
  if (!filePath) return ''
  const parts = filePath.split('/')
  return parts[parts.length - 1]
}

// 组件挂载
onMounted(() => {
  // 尝试加载存储配置，但不显示错误信息（错误信息在上传时显示）
  nextTick(async () => {
    try {
      await loadStorageConfigs()
    } catch (error) {
      // 静默失败，错误会在上传时处理
    }
  })
  initFromModelValue()
})


// 标记是否正在内部更新，防止循环
let isInternalUpdate = false

// 监听 modelValue 变化
watch(() => props.modelValue, () => {
  if (!isInternalUpdate) {
    initFromModelValue()
  }
}, {deep: true})

// 监听已完成文件变化，更新 modelValue
watch(completedFiles, () => {
  isInternalUpdate = true
  updateModelValue()
  nextTick(() => {
    isInternalUpdate = false
  })
}, {deep: true})
</script>

<style scoped lang="scss">
.file-upload {
  .upload-zone {
    border: 2px dashed #dcdfe6;
    border-radius: 6px;
    padding: 40px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: #fafafa;
    margin-bottom: 16px;

    &:hover:not(.upload-zone--disabled) {
      border-color: #409eff;
      background-color: #f0f9ff;
    }

    &--dragover {
      border-color: #409eff;
      background-color: #f0f9ff;
    }

    &--disabled {
      cursor: not-allowed;
      opacity: 0.6;
    }

    &__content {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    &__icon {
      color: #c0c4cc;
      margin-bottom: 16px;
    }

    &__title {
      font-size: 16px;
      color: #303133;
      margin: 0 0 8px 0;
    }

    &__subtitle {
      font-size: 14px;
      color: #909399;
      margin: 4px 0;
    }
  }


  .file-list,
  .uploading-list {
    margin-top: 20px;

    .list-title {
      font-size: 16px;
      color: #606266;
      font-weight: 500;
      margin-bottom: 12px;
    }

    .file-item {
      padding: 12px 16px;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 6px;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      &--error {
        background: #fef0f0;
        border-color: #fbc4c4;
      }

      .file-name {
        font-size: 14px;
        color: #303133;
        margin-bottom: 8px;
        word-break: break-all;
        line-height: 1.4;
      }

      .file-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .file-status {
          display: flex;
          align-items: center;

          .status-text {
            font-size: 12px;
            color: #909399;

            &.success {
              color: #67c23a;
            }

            &.error {
              color: #f56c6c;
            }
          }
        }

        .action-buttons {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .remove-btn {
          --el-button-bg-color: rgba(245, 108, 108, 0.1);
          --el-button-border-color: rgba(245, 108, 108, 0.3);
          --el-button-text-color: #f56c6c;
          --el-button-hover-bg-color: rgba(245, 108, 108, 0.2);
          --el-button-hover-border-color: rgba(245, 108, 108, 0.5);
          --el-button-active-bg-color: rgba(245, 108, 108, 0.3);
        }

        .upload-btn-small {
          --el-button-size: 24px;
        }
      }
    }
  }
}
</style>
